package com.chenjt.jvm.first.ten_GC;

import java.util.ArrayList;
import java.util.List;

/**
 * 注释：
 *
 * @author chenjt
 * @date 2025/6/16 14:30
 */
public class StopTheWorldDemo {


    public static class WorkThread extends Thread{
        List<byte[]> list = new ArrayList<byte[]>();

        public void run(){
            try {
                while(true){
                    for (int i = 0; i < 1000; i++) {
                        byte[] buffer = new byte[1024];
                        list.add(buffer);
                    }

                    if(list.size() > 10000){
                        list.clear();
                        // 会触发full gc，进而会出现STW事件
                        System.gc();
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static class PrintThread extends Thread{
        public final long startTime = System.currentTimeMillis();

        public void run(){
            try {
                while(true){
                    // 每秒打印时间信息
                    long t = System.currentTimeMillis() - startTime;
                    System.out.println(t / 1000 + "." + t % 1000);
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }


    public static void main(String[] args) {
        /**
         * 当触发gc时，PrintThread会出现STW
         * 现象就是本来是每隔1s打印数据的，现在是
         * 1秒多才打印数据
         */
        WorkThread w = new WorkThread();
        PrintThread p = new PrintThread();
        w.start();
        p.start();
    }



}
